package com.gr.staffpm.pages.tasks;

import java.util.Calendar;
import java.util.List;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.gr.staffpm.datatypes.Task;
import com.gr.staffpm.datatypes.TaskComment;
import com.gr.staffpm.datatypes.User;
import com.gr.staffpm.notes.activity.service.IActivityDaoService;
import com.gr.staffpm.security.service.UserService;
import com.gr.staffpm.tasks.service.TaskService;


public class CommentForm extends Form<TaskComment> {

    @SpringBean(name = "activityService")
    private IActivityDaoService activityDaoService;
    @SpringBean(name = "userService")
    private UserService userService;
    private static final long serialVersionUID = 1L;
    private final TextArea<String> comment;
    private final TaskService taskService;
    private final Task task;
    private final List<TaskComment> commentList;

    public CommentForm(String id, TaskService taskService, Task task, List<TaskComment> commentList) {
        super(id, new CompoundPropertyModel<TaskComment>(new TaskComment()));

        this.taskService = taskService;
        this.task = task;
        this.commentList = commentList;

        add(new FeedbackPanel("feedback"));
        comment = new TextArea<String>("comment");
        comment.setOutputMarkupId(true);
        comment.setType(String.class);

        add(comment);
    }

    /**
     * Called upon form submit. Attempts to authenticate the user.
     */
    @Override
    protected void onSubmit() {
        if (comment.getValue() != null && !comment.getValue().isEmpty()) {
            User currentUser = userService.getCurrentUser();
            TaskComment oldComment = getModelObject();
            TaskComment taskComment = new TaskComment(oldComment);
            taskComment.setComment(comment.getValue());
            taskComment.setCreated(Calendar.getInstance().getTime());
            taskComment.setCreatedBy(currentUser);
            taskComment.setTask(task);
            taskComment.setUpdatedBy(currentUser);
            taskComment.setLastUpdated(Calendar.getInstance().getTime());
            taskService.addComment(taskComment);
            commentList.add(taskComment);
            oldComment.setComment("");

            if (!currentUser.equals(task.getAssignee())) {
                activityDaoService.notifyAssigneeOfComment(task, currentUser);
            }
        }
    }

    public TextArea<String> getCommentBox() {
        return comment;
    }

    public Task getTask() {
        return task;
    }
}
